package com.wishu.finance.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.wishu.finance.domain.*;
import com.wishu.finance.enums.*;
import com.wishu.finance.mapper.TCwPaymentPlanMapper;
import com.wishu.finance.mapper.TJrProductMapper;
import com.wishu.finance.mapper.TSfContractMapper;
import com.wishu.finance.service.TSfContractService;
import com.wishu.finance.utils.MyJinRongUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 25813
 * @description 针对表【t_sf_contract】的数据库操作Service实现
 * @createDate 2023-04-26 15:03:04
 */
@Service
public class TSfContractServiceImpl extends ServiceImpl<TSfContractMapper, TSfContract>
        implements TSfContractService {

    @Resource
    TCwPaymentPlanMapper tCwPaymentPlanMapper;
    @Resource
    TJrProductMapper tJrProductMapper;

    @Override
    public IPage<TSfContract> selectPageVo(IPage<?> page, TSfContract contract) {
        return baseMapper.selectPageVo(page, contract);
    }

    // 查询收房分期 - 付款计划（ 已付款）
    private int getCwPaymentPlanPaidCount(Long sfContractId) {
        Map<String, Object> param = new HashMap<>();
        //收房
        param.put("contract_type", ContractTypeEnum.SF.getIndex());
        //收房合同ID
        param.put("contract_id", sfContractId);
        //收房付款单
        param.put("pay_type", PaymentTypeEnum.SFFK.getIndex());
        //已付款
        param.put("pay_state", PayStatusEnum.YFK.getIndex());
        //普通账单
        param.put("bill_type", PayPlanZdType.PTZD.getIndex());
        //租金
        param.put("item_type", BusinessCostTypesEnum.ZUJIN.getIndex());
        return tCwPaymentPlanMapper.selectByMap(param).size();

    }

    // 查询收房分期
    private List<TCwPaymentPlan> getCwPaymentPlanList(Long sfContractId) {
        Map<String, Object> param = new HashMap<>();
        //收房
        param.put("contract_type", ContractTypeEnum.SF.getIndex());
        //收房合同ID
        param.put("contract_id", sfContractId);
        //收房付款单
        param.put("pay_type", PaymentTypeEnum.SFFK.getIndex());
        //未付款
        param.put("pay_state", PayStatusEnum.WFK.getIndex());
        //普通账单
        param.put("bill_type", PayPlanZdType.PTZD.getIndex());
        //租金
        param.put("item_type", BusinessCostTypesEnum.ZUJIN.getIndex());
        return tCwPaymentPlanMapper.selectByMap(param);
    }

    @Override
    public SfContractDetailsResponseDTO contractListById(Long id) {
        TSfContract sfce = baseMapper.selectById(id);
        SfContractDetailsResponseDTO sfdto = new SfContractDetailsResponseDTO();
        //将sfce数据拷贝到sfdto里
        BeanUtils.copyProperties(sfce, sfdto);
        // 查询收房分期
        List<TCwPaymentPlan> payList = getCwPaymentPlanList(id);
        double balance = 0;
        Date startDate = null;
        if (payList.size() > 0) {
            for (TCwPaymentPlan r : payList) {
                //累加付款金额
                balance = MyJinRongUtils.add(balance, r.getPaymentAmount().doubleValue());
                if (null == startDate) {
                    //并获取第一笔付款记录的付款日期作为租赁开始日期
                    startDate = r.getPaymentDaysBegin();
                } else if (1 == startDate.compareTo(r.getPaymentDaysBegin())) {
                    startDate = r.getPaymentDaysBegin();
                }
            }
        }
        //获取合同的租赁结束日期
        Date endDate = sfce.getLeaseEndTime();
        // 拼接房产信息   = 小区名称+ 房产信息
        String houseName = sfdto.getPremiseName() + sfdto.getHouseName();
        sfdto.setHouseName(houseName);
        sfdto.setEndDate(endDate);
        sfdto.setStartDate(startDate);
        // 根据一段时间区间，按月份拆分成多个时间段
        List<MyJinRongUtils.KeyValueForDate> splitMonth = MyJinRongUtils.getSplitMonthForDate(startDate, endDate);
        if (null == splitMonth) {
            sfdto.setPeriods(0);
        } else {
            // 期数
            sfdto.setPeriods(splitMonth.size());
        }
        // 查询收房分期 - 付款计划（ 已付款）
        int count = getCwPaymentPlanPaidCount(id);
        //根据已付款记录数量判断是否需要计算借款金额和期数
        if (count == 0) {
            //根据付款总金额和时间段数量计算出每期需还款金额
            double div = MyJinRongUtils.div(balance, splitMonth.size(), 2);
            //并减去第一期的金额
            balance = MyJinRongUtils.sub(balance, div);
            Calendar cl = Calendar.getInstance();
            cl.setTime(sfdto.getStartDate());
            // 不加一个月
            cl.add(Calendar.MONTH, 1);
            //更新 sfdto 的开始日期
            sfdto.setStartDate(cl.getTime());
            // 期数 减1
            sfdto.setPeriods(splitMonth.size() - 1);
            //sfdto.setPeriods(splitMonth.size());
            // 借款金额
            sfdto.setBalance(balance);
            // 授信额
            sfdto.setSxBalance(balance);
        } else {
            //如果有已付款记录，则直接将借款金额和授信额度设置为 balance 和 sxBalance
            // 借款金额
            sfdto.setBalance(balance);
            // 授信额
            sfdto.setSxBalance(balance);
        }
        return sfdto;
    }

    @Override
    public SfContractDetailsResponseDTO getSfContractStagingCalculation(Long contractId, Long productId) {
        //根据合同ID查询数据
        TSfContract sfce = baseMapper.selectById(contractId);
        SfContractDetailsResponseDTO sfdto = new SfContractDetailsResponseDTO();
        //把sfce数据拷贝到sfdto
        BeanUtils.copyProperties(sfce, sfdto);
        // 查询收房分期
        List<TCwPaymentPlan> payList = getCwPaymentPlanList(contractId);
        //根据金融分期ID查询数据
        TJrProduct product = tJrProductMapper.selectById(productId);
        // 计算授信额
        Double creditLine = MyJinRongUtils.div(product.getCreditLine().doubleValue(), 100, 2);
        double balance = 0;
        if (payList.size() > 0) {
            for (TCwPaymentPlan pay : payList) {
                //累加收房分期总金额
                balance = MyJinRongUtils.add(balance, pay.getPaymentAmount().doubleValue());
            }
        }
        // 获取期数
        int size = payList.size();
        Integer paymentType = sfce.getPaymentType();
        double period = MyJinRongUtils.mul(size, paymentType);
        // 期数
        sfdto.setPeriods(new Double(period).intValue());
        // 总金额
        sfdto.setBalance(balance);
        // 授信总额
        double sxBalance = MyJinRongUtils.mul(sfdto.getBalance(), creditLine);
        sfdto.setSxBalance(sxBalance);
        return sfdto;
    }

    @Override
    public ResponseDetailSfContractDto detailSfContract(String cfContractId) {
        // 查询收房合同信息
        TSfContract sfContractEntity = baseMapper
                .selectSearchById(cfContractId);
        ResponseDetailSfContractDto responseDetailSfContractDto = new ResponseDetailSfContractDto();
        BeanUtils.copyProperties(sfContractEntity, responseDetailSfContractDto);
        // 查询付款计划表
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("contract_id", cfContractId);
        hashMap.put("contract_type", ContractTypeEnum.SF.getIndex());
        hashMap.put("item_type", BusinessCostTypesEnum.ZUJIN.getIndex());
        List<TCwPaymentPlan> entityList = tCwPaymentPlanMapper.selectByMap(hashMap);
        ArrayList<PaymentDto> paymentList = new ArrayList<PaymentDto>();
        PaymentDto paymentDto = null;
        if (null != entityList && entityList.size() > 0) {
            for (TCwPaymentPlan record : entityList) {
                paymentDto = new PaymentDto();
                BeanUtils.copyProperties(record, paymentDto);
                paymentDto.setPaymentId(record.getId());
                paymentList.add(paymentDto);
            }
        }
        // 续约时，结束时间加1
        Calendar c = Calendar.getInstance();
        Date leaseEndTime = responseDetailSfContractDto.getLeaseEndTime();
        c.setTime(leaseEndTime);
        c.add(Calendar.DATE, 1);
        leaseEndTime = c.getTime();
        responseDetailSfContractDto.setLeaseEndTime(leaseEndTime);
        responseDetailSfContractDto.setPaymentList(paymentList);
        return responseDetailSfContractDto;
    }
}




